package com.lineengine.lineengine.result;

import com.lineengine.lineengine.common.ErrorType;
import com.lineengine.lineengine.context.IContext;
import com.lineengine.lineengine.context.MyContext;
import com.lineengine.lineengine.common.CommonErrorCode;
import com.lineengine.lineengine.common.IErrorCode;

/**
 * CommonResult
 *
 * @author wenrong.yu
 */
public class CommonResult<T extends IContext<T>> extends DefaultResult<T> {
    /**
     * success()
     */
    private static CommonResult<MyContext> commonSuccessResult;

    public CommonResult() {
    }

    /**
     * 构造方法
     *
     * @param success 是否成功
     * @param code    错误码
     * @param message 消息
     */
    private CommonResult(ErrorType errorType, boolean success, String code, String message) {
        super(errorType, success, code, message);
    }

    /**
     * 成功
     *
     * @return 成功response
     */
    public static CommonResult<MyContext> success() {
        if (commonSuccessResult != null) {
            return commonSuccessResult;
        }
        commonSuccessResult = new CommonResult<MyContext>(ErrorType.NONE,
                true,
                CommonErrorCode.SUCCESS.getCode(),
                CommonErrorCode.SUCCESS.getMessage());
        return commonSuccessResult;
    }

    /**
     * 失败
     *
     * @param errorCode 响应码
     * @return CommonResult
     */
    public static CommonResult<MyContext> fail(ErrorType errorType, IErrorCode errorCode, Object... messageArgs) {
        return new CommonResult<>(errorType, false, errorCode.getCode(), errorCode.getMessage(messageArgs));
    }

    /**
     * 失败
     *
     * @param response 响应
     * @return CommonResult
     */
    public static CommonResult<MyContext> from(DefaultResponse<?> response) {
        if (response.isSuccess()) {
            return success();
        }
        return new CommonResult<>(response.getErrorType(), false, response.getCode(), response.getMessage());
    }
}
